import frappe
import datetime
from werkzeug.wrappers import Response
import xml.etree.ElementTree as ET


@frappe.whitelist(allow_guest=True)
def get_doc_asxml(doc_name):
    doc = frappe.get_doc('T001', doc_name)
    doc_dict = doc.as_dict(convert_dates_to_str=True)
    # 创建根元素
    root = ET.Element("data")
    for key, value in doc_dict.items():
        if isinstance(value, list):
            #添加子表
            child = ET.SubElement(root, key)
            # child.set("name", key)  # 设置属性
            for sub_dict in value:
                for subkey, subvalue in sub_dict.items():
                    # 添加子元素
                    subitem = ET.SubElement(child, subkey)
                    # subitem.set("name", subkey)  # 设置属性
                    subitem.text = str(subvalue)  # 设置文本  
        else:
            # 添加子元素
            item = ET.SubElement(root, key)
            # item.set("name", key)  # 设置属性
            item.text = str(value)  # 设置文本       
    # 将XML文档转换为字符串
    xml_string = ET.tostring(root)
    response = Response(xml_string, content_type='application/xml')
    response.status_code = 200
    return response